<?php
namespace app\base\service;
use think\Controller;
use app\circle\model\UserFriend;
use think\facade\Log;
use app\base\model\BaseModel;
use think\Session;
use think\facade\Cache;
/**
 * 
 */
class BaseService extends Controller
{
	protected $user = array();
	protected $token ='';
	protected $path='';
	protected $base = '';
	protected $host = 'https://aiwo.yundao88.com';
 	public function __construct($sessionid='')
	 {

	 	$this->path=$_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR;


	 	$this->user =array("Identity"=>"0",
"Ismaincreate"=>null,
"Logintime"=>1541147552,
"Openid"=>"oBPCo5Uv1ZzVjGC8QsQ72KqHFTPg",
"Regtime"=>1541147552,
"Token"=>"cb0e5879443a5dc4bc8a17264f6307f5",
"UserImg"=>"http=>/wx.qlogo.cn/mmopen/vi_32/aZ5e2nTY0tedib34y89jhx60L3HKzqVGcekQjpblXr4ZPXicO6uq48UcY5OBvauvySfEoY0vmUnVcqo2Bn0uDVGw/132",
"Userid"=>27,
"Usernickname"=>"凌大魔王啊",
"Userphone"=>null,
"address"=>"湖南平江",
"birthday"=>"1968",
"currToken"=>"cb0e5879443a5dc4bc8a17264f6307f5",
"energy"=>0,
"pinyin"=>"无尽流年",
"popularVal"=>0,
"sex"=>1,
"wxnickname"=>"无尽流年");
	 	$this->token=$this->set_token();	
	 	$this->base = new BaseModel; 	
	 }
	//通过openid获得该用户的所有信息，使用了缓存，每次更改用户信息后需要更新缓存
	protected function get_userinfo($Openid=''){

		$data = Cache::get($Openid);
		if(!empty($data)) return $data;
		$where['Openid'] = $Openid;
		$userinfo = $this->base->findOnCache('userinfo',$where,"*",$Openid,1800);
		return $userinfo;
	}

	protected function return_code($code='400',$msg='错误',$data=array()){
		$res['code']=$code;
		$res['msg']=$msg;
		if(!empty($data)){
			$res['data'] = $data;
		}
		return $res;
	}

	//图片批量上传
	public function upload_img($files){
		$res['code']=400;
		$res['msg']='失败';
		$res['imagepath']=[];
		//log::write($files);
		// $res['path']=[];
		 // 获取表单上传文件
	    foreach($files as $file ){
	        // 移动到框架应用根目录/uploads/ 目录下
	         $info = $file->validate(['ext'=>'jpg,png,gif'])->move($this->path);
	        if($info){
	            // 成功上传后 获取上传信息
	            $res['imagepath'][] =$this->host.DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR.$info->getSaveName();
	            $res['code']=200;
	             $res['msg']='成功';
	        }else{
	            // 上传失败获取错误信息
	            $res['code']=300;
	            $res['msg']=$file->getError(); 
	            
	        } 

		unset($info);  
	        
	    }
	     return $res; 
	}

	// 视频上传
	public function upload_one_video($file){
		$res['code']=400;
		$res['msg']='失败';
		$res['imagepath']='';
		//log::write($files);
		// $res['path']=[];
		 // 获取表单上传文件
	        // 移动到框架应用根目录/uploads/ 目录下
	         $info = $file->validate(['ext'=>'mp4,avi'])->move($_SERVER['DOCUMENT_ROOT'] . DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR);
	        if($info){
	            // 成功上传后 获取上传信息
	            $res['imagepath'] = $this->host.DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR.$info->getSaveName();
	            $res['code']=200;
	             $res['msg']='成功';
	        }else{
	            // 上传失败获取错误信息
	            $res['code']=300;
	            $res['msg']=$file->getError(); 
	            return $res;
	        }   
	        
	    
	     return $res; 
	}
//单张图片上传
		//图片批量上传
	public function upload_one_img($file){
		$res['code']=400;
		$res['msg']='失败';
		$res['imagepath']='';
		//log::write($files);
		// $res['path']=[];
		 // 获取表单上传文件
	        // 移动到框架应用根目录/uploads/ 目录下
	         $info = $file->validate(['ext'=>'jpg,png,gif'])->move($this->path);
	        if($info){
	            // 成功上传后 获取上传信息
	            $res['imagepath'] =$this->host.DIRECTORY_SEPARATOR . 'uploads' . DIRECTORY_SEPARATOR.$info->getSaveName();
	            $res['code']=200;
	             $res['msg']='成功';
	        }else{
	            // 上传失败获取错误信息
	            $res['code']=300;
	            $res['msg']=$file->getError(); 
	            return $res;
	        }   
	        
	    
	     return $res; 
	}
	//删除目录和文件
	protected function delDirAndFile($file, $delDir = FALSE) {
		$path=$this->path.$file;
	    if (is_array($path)) {
	        foreach ($path as $subPath)
	            delDirAndFile($subPath, $delDir);
	    }
	    if (is_dir($path)) {
	        $handle = opendir($path);
	        if ($handle) {
	            while (false !== ( $item = readdir($handle) )) {
	                if ($item != "." && $item != "..")
	                    is_dir("$path/$item") ? delDirAndFile("$path/$item", $delDir) : unlink("$path/$item");
	            }
	            closedir($handle);
	            if ($delDir){
	            	clearstatcache();
	                return rmdir($path);
	            }
	        }
	    } else {
	        if (file_exists($path)) {
	        	clearstatcache();
	            return unlink($path);
	        } else {
	        	clearstatcache();
	            return FALSE;
	        }
	    }
	    clearstatcache();
	}
	 
	
	
	//删除单个文件方法看看
	protected function del_file($filepath){
	    $filename = $this->path.$filepath;
	    log::write($filename);
	    if(file_exists($filename)){
	        unlink($filename);
	    }else{
	        return FALSE;
	    }
	    return TRUE;
	}


	//设置家庭token
	protected function set_token(){
		return  md5($this->user['Userid'].time().$this->user['Openid'].rand(0,999));
	}


	//判断权限  
 	public function permissions($openid=''){
		$res['code'] = 10004;
		$res['msg'] = "没有关系";
		$where_home['Openid2']=$this->user['Openid'];//邀请人的openid 登录用户的openid
		$where_home['Openid1']=$openid;//主邀请人
		$where_f['openid1']=$this->user['Openid'];
    	$where_f['openid2']=$openid;
	    $where_t['openid1']=$openid;
	    $where_t['openid2']=$this->user['Openid'];
		if($this->user['Openid'] == $openid||empty($openid)){
			$res['code'] = 10000;
			$res['msg'] = "登陆用户与当前用户是同一个";
			return $res;
		}else if($this->base->countWhere('home_token',$where_home)>0){//家庭成员关系 Openid1 邀请人id 被邀请人Openid2
			$res['code'] = 10001;
			$res['msg'] = "登陆用户与当前用户是家人关系";
			return $res;
		}else if($this->base->is_friend($where_f,$where_t) >0 ){//是不是好友关系
			$res['code'] = 10002;
			$res['msg'] = "登陆用户与当前用户是好友关系";
			return $res;
		}
		return $res;

	}

		//CURL请求封装
		/**
	 * 提交数据 
	 * @param  string $url 请求Url
	 * @param  string $method 请求方式
	 * @param  array/string $headers Headers信息 
	 * @param  array/string $params 请求参数
	 * @return 返回的
	 */
	function curlRequest($url, $method, $headers, $params){
	    if (is_array($params)) {
	        $requestString = http_build_query($params);
	    } else {
	        $requestString = $params ? : '';
	    }
	    if (empty($headers)) {
	        $headers = array('Content-type: text/json'); 
	    } elseif (!is_array($headers)) {
	        parse_str($headers,$headers);
	    }
	    // setting the curl parameters.
	    $ch = curl_init();
	    curl_setopt($ch, CURLOPT_URL, $url);
	    curl_setopt($ch, CURLOPT_VERBOSE, 1);
	    
	    // turning off the server and peer verification(TrustManager Concept).
	    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
	    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
	    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
	    curl_setopt($ch, CURLOPT_POST, 1);
	    // setting the POST FIELD to curl
	    switch ($method){  
	        case "GET" : curl_setopt($ch, CURLOPT_HTTPGET, 1);
	        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
	        break;  
	        case "POST": curl_setopt($ch, CURLOPT_POST, 1);
	                     curl_setopt($ch, CURLOPT_POSTFIELDS, $requestString);
	                     array_push($headers, 'Content-Length: ' . strlen($requestString));
	                     curl_setopt($ch, CURLOPT_HTTPHEADER,$headers);
	                     break;  
	        case "PUT" : curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "PUT");   
	                     curl_setopt($ch, CURLOPT_POSTFIELDS, $requestString);
	                     break;  
	        case "DELETE":  curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, "DELETE");   
	                        curl_setopt($ch, CURLOPT_POSTFIELDS, $requestString);
	                        break;  
	    }
	    // getting response from server
	    $response = curl_exec($ch);
	   
	    //close the connection
	    curl_close($ch);
	    
	    //return the response
	    if (stristr($response, 'HTTP 404') || $response == '') {
	        return array('Error' => '请求错误');
	    }
	    return $response;
	} 

}
?>